package com.power.sifa;

import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.ding.api.Di_userFeign;
import com.plf.common.domain.YesNo;
import com.plf.common.utils.PdfConvertUtil;
import com.plf.common.utils.StringUtil;
import com.plf.common.utils.WordUtil;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.base.service.Ha_attachmentService;
import com.power.sifa.approve.dao.BusinessApproveDao;
import com.power.sifa.approve.model.Apl_admre_audit;
import com.power.sifa.approve.model.Apl_admreview;
import com.power.sifa.approve.model.Apl_main;
import com.power.sifa.approve.model.Aprv_process_materials;
import com.power.sifa.approve.model.enumeration.*;
import com.power.sifa.approve.service.Apl_admre_auditService;
import com.power.sifa.approve.service.Apl_admreviewService;
import com.power.sifa.approve.service.Apl_mainService;
import com.power.sifa.approve.service.Aprv_process_materialsService;
import com.power.sifa.net.service.ApplyService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Slf4j
@SpringBootTest
public class TescAccept {

    @Resource
    private Apl_admre_auditService apl_admre_auditService;
    @Resource
    private Apl_mainService apl_mainService;
    @Resource
    private ApplyService applyService;
    @Resource
    private Ha_attachmentService ha_attachmentService;
    @Resource
    private Aprv_process_materialsService aprv_process_materialsService;
    @Resource
    private Apl_admreviewService apl_admreviewService;
    @Resource
    private BusinessApproveDao businessApproveDao;
    @Resource
    private Di_userFeign di_userFeign;

    @Test
    @Transactional(rollbackFor = Exception.class)
    void test() throws Exception {
//        this.apl_dossierService.buildInitDossier("1699603339571Q2BvgezMRv-HE7g_wxjpG");
//        this.apl_archiveService.initialArchiveData("1699603339571Q2BvgezMRv-HE7g_wxjpG");
//        this.apl_dossierService.updateDossier("1699603339571Q2BvgezMRv-HE7g_wxjpG");
//        log.info("初始化成功");


//        Ha_attachment attObj = this.BusinessApproveService.createArchiveCover("1696484934718kfl0W-R_MZtGO-588dP4L");
//        log.info("生成成功:{}", attObj.getId());
//        this.apl_mainService.queryBusineTree("1699603339571Q2BvgezMRv-HE7g_wxjpG", "3601001002");
//        Ha_user_approvePageInfo pageInfo = new Ha_user_approvePageInfo();
//        pageInfo.setType(1);
//        this.iHa_user_approveServiceImpl.findUserTree("3601001000", pageInfo);

        // 1. 查询子流程的表单数据
//        Apl_main mainObj = apl_mainService.getById("1711348908450BoJA10tbQe7h0FO-178wb");
//        Apl_admre_audit auditObj = this.apl_admre_auditService.getById("1711348908450BoJA10tbQe7h0FO-178wb");
        // 2. 生成并上传文件
//        this.generateDocuments(auditObj, mainObj.getFormid());
        // 期满日期测试
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        String datex = this.businessApproveDao.expiryDate(format.parse("2024-03-01"), 60);
//        log.info("datex -> {}", datex);
    }

    public void generateDocuments(Apl_admre_audit auditObj, String formid) throws Exception {
        // 2. 生成并上传文件
        Ha_attachment attachment;
        Map<String, Object> formData = this.applyService.formLoadField(formid, "1711348908450BoJA10tbQe7h0FO-178wb");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatT = new SimpleDateFormat("yyyy年M月d日");
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_firstdate"))) {
            formData.put("apl_admre_audit_firstdate", formatT.format(format.parse((String) formData.get("apl_admre_audit_firstdate"))));
        }
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_seconddate"))) {
            formData.put("apl_admre_audit_seconddate", formatT.format(format.parse((String) formData.get("apl_admre_audit_seconddate"))));
        }
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_thirddate"))) {
            formData.put("apl_admre_audit_thirddate", formatT.format(format.parse((String) formData.get("apl_admre_audit_thirddate"))));
        }
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_fourthdate"))) {
            formData.put("apl_admre_audit_fourthdate", formatT.format(format.parse((String) formData.get("apl_admre_audit_fourthdate"))));
        }
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_fivedate"))) {
            formData.put("apl_admre_audit_fivedate", formatT.format(format.parse((String) formData.get("apl_admre_audit_fivedate"))));
        }
        formData.put("apl_admreview_hearsecondname", "廖悦辰");

        byte[] pdfByte;
        {
            try {
//                WordUtil wordUtil = new WordUtil("AdmreAuditInside.docx");
//                WordUtil wordUtil = new WordUtil("AdmreAuditInCharge.docx");
//                WordUtil wordUtil = new WordUtil("AdmreAuditPrincipal.docx");
                WordUtil wordUtil = new WordUtil("ThreeLevelApprove.docx");
                wordUtil.replaceTable(formData);
                OutputStream os = wordUtil.createWord();
                InputStream is = new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray());
                pdfByte = PdfConvertUtil.word2pdfWithFont(is);
                attachment = ha_attachmentService.upload(new ByteArrayInputStream(pdfByte), "案件受理审批表.pdf");
                log.info("AdmreAuditAccept 案件受理审批表生成并保存成功 -> {}", attachment.getId());
            } catch (Exception e) {
                log.error("AdmreAuditAccept 案件受理审批表生成并保存失败 ->  msg[{}]", e.getMessage());
                throw new RuntimeException("AdmreAuditAccept 案件受理审批表生成并保存失败 -> " + e.getMessage());
            }

            // 3. 保存审批系统文书, 只存父流程
            Aprv_process_materials docObj = new Aprv_process_materials(Tp_procmaterialEnum.ADMRE_APPROVE);
            docObj.setId(auditObj.getApplyid() + NanoIdUtils.randomNanoId());
            // 通知书类型枚举
            docObj.setMattype(Tp_procmaterial.ADMRE_APPROVE);
            docObj.setAttachid(attachment.getId());
            docObj.setCreateuserid("");
            docObj.setCreateuser("");
            docObj.setCreatetime(new Date());
            docObj.setApplyid(auditObj.getApplyid());
            docObj.setType(Tp_proctype.ACCEPT_ACCEPT);
            this.aprv_process_materialsService.saveOrUpdate(docObj);
        }

        // 通知书补充字段
        Apl_admreview admreObj = this.apl_admreviewService.getById(auditObj.getApplyid());
        // 判断行为
        if (YesNo.YES == admreObj.getIsomission()) {
            formData.put("behavior", "不履行法定职责");
        } else {
            if (Tp_admpr.OTHER.getKey().equals(admreObj.getPrtype())) {
                formData.put("behavior", admreObj.getPrname());
            } else {
                formData.put("behavior", Tp_admpr.getByKey(admreObj.getPrtype()).getDescription());
            }
            // 拼接行政行为文号
            if (!StringUtil.isEmpty(admreObj.getPrcode())) {
                formData.put("prcode", "（编号：" + admreObj.getPrcode() + "）");
            } else {
                formData.put("prcode", "");
            }
        }
        // 提交时间
        Apl_main faMainObj = apl_mainService.getById(auditObj.getApplyid());
        formData.put("subtime", formatT.format(format.parse(faMainObj.getSubtime())));
        // 当前时间
        formData.put("today", formatT.format(new Date()));

    }

}
